<template>
  <div class="workscheduling-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="item.label" :name="index + ''" v-for="(item, index) in tabList" :key="index"></el-tab-pane>
    </el-tabs>
    <div style="padding: 10px; display: flex;align-items: center;justify-content: space-between;">
      <div style="display: flex;align-items: center;">
        <span>请选择排样需要的板材</span>
        <el-tag style="margin:0 10px;">已选：{{ multipleSelection.length }}</el-tag>
      </div>
      <div>
        <el-button type="primary" size="small" @click="reset">全部重置</el-button>
        <el-button type="primary" icon="el-icon-document-add" size="small">添加自动工艺</el-button>
      </div>
    </div>
    <el-table :data="tableData" ref="warehouseTable" height="65vh" style="width: 100%" border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="数量" width="160" align="center">
        <template slot-scope="scope">
          <el-input-number v-model.trim="scope.row.numVal" :precision="0" :min="0" :max="scope.row.syInv" :step="1"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column align="center">
        <template slot="header">
          <header-filter title="板材名称" :current-sort="currentSort" props="name" :filter-change="filterChange"
            :filters="filters.name" /> 
        </template>
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="缩略图" align="center" width="120">
        <template slot-scope="scope">
          <el-image style="width: 80px; height: 80px;" :src="getAssteImage(scope.row.previewUrl)" fit="contain"
            :preview-src-list="[getAssteImage(scope.row.previewUrl)]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center">
        <template slot="header">
          <header-filter title="材质" :current-sort="currentSort" props="material" :filter-change="filterChange"
            :filters="filters.material" /> 
        </template>
        <template slot-scope="scope">{{ scope.row.material }}</template>
      </el-table-column>
      <el-table-column  width="140" align="center">
        <template slot="header">
          <header-filter title="厚度(mm)" :filters="filters.thick" sortable :current-sort="currentSort" props="thick" :filter-change="filterChange" />
        </template>
        <template slot-scope="scope">{{scope.row.thick}}</template> 
      </el-table-column>
      <el-table-column  align="center" width="180"> 
        <template slot="header">
          <header-filter title="长-Y(mm)" sortable props="length" :current-sort="currentSort" :filter-change="filterChange"
            :filters="filters.lengths" />
        </template>
        <template slot-scope="scope">{{ scope.row.length }}</template>
      </el-table-column>
      <el-table-column  align="center" width="200">
        <template slot="header">
          <header-filter title="宽-X(mm)" sortable :current-sort="currentSort" props="width" :filter-change="filterChange"
            :filters="filters.width" />
        </template>
        <template slot-scope="scope">{{ scope.row.width }}</template>
      </el-table-column>
      <el-table-column width="180" align="center">
        <template slot="header">
          <header-filter title="剩余库存" sortable :current-sort="currentSort" props="syInv" :filter-change="filterChange" />
        </template>
        <template slot-scope="scope">{{ scope.row.syInv }}</template>
      </el-table-column> 
      <el-table-column align="center" show-overflow-tooltip>
        <template slot="header">
          <header-filter title="仓库" :current-sort="currentSort" props="warename" :filter-change="filterChange"
            :filters="filters.warename" />
        </template>
        <template slot-scope="scope">{{ scope.row.ware ? scope.row.ware.name : '' }}</template>
      </el-table-column>
      <el-table-column label="合同号" align="center" width="120">
        <template slot-scope="scope">{{ scope.row.contractNo }}</template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer" style="padding-top:10px;">
      <el-button @click="handleShare">取 消</el-button>
      <el-button type="primary" @click="submitMethod">确 定</el-button>
    </span>
  </div>

</template>

<script>
import { uniq, findIndex, clone, uniqBy, isNumber,orderBy,isPlainObject} from 'lodash';
import { mapState } from 'vuex';
import HeaderFilter from '@/components/headerFilter/HeaderFilter.vue';
import globalJs from '@/utils/global';
export default {
  name: 'Workscheduling',
  components:{HeaderFilter},
  props: {
    partList: {
      type: Array,
      default: []
    },
    close: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentSort:'',
      tableData: [],
      activeName: '0',
      warehouse: [],
      multipleSelection: [],
      tabList: [],
      filters: {
        material: [],
        lengths: [],
        width: [],
        name: [],
        warename:[],
        thick:[]
      },
      filterVals: {
        material: [],
        length: [],
        width: [],
        name: [],
        warename:[],
        thick:[]
      },
    };
  },
  filters: {
    formDate: (val) => {
      return global.getdate1(val);
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.app.userInfo,
      uploadLayoutInfo:state =>state.resource.uploadLayoutInfo
    }),
  },
  watch: {
    partList: {
      deep: true,
      handler: function (val) {
        if (Array.isArray(val) && val.length > 0) {
          if (this.warehouse.length > 0) {
            this.initAjaxMethod();
          } else {
            this.initAjaxWarehouse();
          }
        }
      },
    },
  },
  mounted() {
    if (Array.isArray(this.partList) && this.partList.length > 0) {
      if (this.warehouse.length > 0) {
        this.initAjaxMethod();
      } else {
        this.initAjaxWarehouse();
      }
    }
  },
  methods: {
    //仓库
    initAjaxWarehouse() {
      this.loading = true;
      this.$http
        .get(this.$API.GET_USER_WARE, { userId: this.userInfo.id })
        .then((res) => {
          this.loading = false;
          let list = Array.isArray(res.data) ? res.data : [];
          if (list.length > 0) {
            this.warehouseStockAjaxMethod(list);
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    //库存
    warehouseStockAjaxMethod(keys) {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.GET_USER_STOCK + '?' + keys.map(o => 'warehouseIds=' + o.id).join('&'))
        .then(res => {
          loading.close();
          let warehouse = Array.isArray(res.data) ? res.data : [];
          this.warehouse = warehouse;
          this.initAjaxMethod();
        })
        .catch(err => {
          loading.close();
        });
    },
    initAjaxMethod() {
      let tabs = [];
      this.partList.forEach(item => {
        if (item.part) {
          tabs.push({
            material: item.part.material,
            thick: item.part.thick,
            gas: item.part.gas,
            value: item.part.material + '-' + item.part.thick + '-' + item.part.gas,
            label: this.getPaneLabel(item.part),
            childer: [],
            taskParts: [],
            id: item.part ? item.part.id : '',
            name: item.part ? item.part.name : '',
            drawingUrl: item.part ? item.part.drawingUrl : '',
            bcQty: item.bcQty,
            part:item
          });
        }
      });
      let uniqTabs = uniqBy(tabs, o => o.value);
      uniqTabs.forEach(item => {
        this.warehouse.forEach(val => {
          if (item.material === val.material && item.thick === val.thick) {
            item.childer.push(val);
          }
        });
        tabs.forEach(val => {
          if (item.value === val.value) {
            item.taskParts.push(val.part);
          }
        });
      });
      if (tabs.length > 0) {
        this.tabList = uniqTabs;
        this.handleClick();
      }
    },
    handleShare() {
      this.$emit('update:close', false);
    },
    handleClick() {
      this.reset();
      let material = [], length = [], width = [], name = [],warename=[],thick=[],tableData=this.tabList[this.activeName].childer;
      tableData.forEach(item => {
        item.syInv = (isNumber(Number(item.actualInv)) ? item.actualInv : 0) - (isNumber(Number(item.lockInv)) ? item.lockInv : 0) - (isNumber(Number(item.useInv)) ? item.useInv : 0);
        if (item.ware) {
          warename.push(item.ware.name);
        }
        item.numVal=item.syInv;
        name.push(item.name);
        material.push(item.material);
        length.push(item.length);
        width.push(item.width);
        thick.push(item.thick);
      });
      this.filters.material = uniq(material).map(o => { return { text: o, value: o }; });
      this.filters.lengths = uniq(length).map(o => { return { text: o, value: o }; });
      this.filters.width = uniq(width).map(o => { return { text: o, value: o }; });
      this.filters.name = uniq(name).map(o => { return { text: o, value: o }; });
      this.filters.warename = uniq(warename).map(o => { return { text: o, value: o }; });
      this.filters.thick = uniq(thick).map(o => { return { text: o, value: o }; });
      this.tableData = tableData;
    },
    filterChange(code, type, value) {       
      if (type === 'checkBox') {
        if (code === 'material') {
          this.filterVals.material = value;
        } else if (code === 'name') {
          this.filterVals.name = value;
        } else if (code === 'length') {
          this.filterVals.length = value; 
        } else if (code === 'width') {
          this.filterVals.width = value;
        } else if (code === 'warename') {
          this.filterVals.warename = value;
        }else if (code === 'thick') {
          this.filterVals.thick = value;
        }
        // console.log('this.filterVals',this.filterVals); 
        this.filterHandler();
      } else if (type === 'sort') {
        this.currentSort=code;
        let sourceData=[];
        if (code === 'length'){  
          sourceData=orderBy(clone(this.tableData), 'length', value);
        }else if(code === 'width'){
          sourceData=orderBy(clone(this.tableData), 'width', value);
        }else if(code === 'syInv'){
          sourceData=orderBy(clone(this.tableData), 'syInv', value);
        }else if(code === 'thick'){
          sourceData=orderBy(clone(this.tableData), 'thick', value);
        }
        this.tableData=sourceData;
      }
    },
    filterHandler() {
      let materials = [],lengths = [],widths = [],names = [],warenames=[],thicks=[],
        { material, length, width, name,warename,thick} = this.filterVals,
        orignData = this.tabList[this.activeName].childer;
      if (material.length > 0) {
        orignData.forEach(item => {
          let materialsIndex = findIndex(material, o => o == item.material);
          if (materialsIndex > -1) {
            materials.push(item);
          }
        });
      } else {
        materials = orignData;
      }

      if (length.length > 0) {
        materials.forEach(item => {
          let lengthsIndex = findIndex(length, o => o == item.length);
          if (lengthsIndex > -1) {
            lengths.push(item);
          }
        });
      } else {
        lengths = materials;
      }

      if (width.length > 0) {
        lengths.forEach(item => {
          let widthIndex = findIndex(width, o => o == item.width);
          if (widthIndex > -1) {
            widths.push(item);
          }
        });
      } else {
        widths = lengths;
      }

      
      if (name.length > 0) {
        widths.forEach(item => {
          let nameIndex = findIndex(name, o => o == item.name);
          if (nameIndex > -1) {
            names.push(item);
          }
        });
      } else {
        names = widths;
      }

      if (warename.length > 0) {
        names.forEach(item => {
          let warenamesIndex = findIndex(warename, o => o == item.ware.name);
          if (warenamesIndex > -1) {
            warenames.push(item);
          }
        });
      } else {
        warenames = names;
      }

      if (thick.length > 0) {
        warenames.forEach(item => {
          let thicksIndex = findIndex(thick, o => o == item.thick);
          if (thicksIndex > -1) {
            thicks.push(item);
          }
        });
      } else {
        thicks = warenames;
      }

      
      this.tableData = thicks;
      this.$forceUpdate();
    },
    //重置
    reset() {
      this.$store.dispatch('app/clearTableHeaderFilter');
      this.tableData = this.tabList[this.activeName].childer;
      this.currentSort='';
    },
    async submitMethod() {
      if (this.uploadLayoutInfo && isPlainObject(this.uploadLayoutInfo)) {
        this.$confirm('当前CAD正在排样中,请完成后再操作！', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
        });
        return false;
      }
      if (this.multipleSelection.length === 0) return this.$message.error('请选择库存');
      let tabsItem = this.tabList[this.activeName], isAllNumAdd = true, stocks = [],lockData=[],formTaskParts=[];
      tabsItem.childer.forEach(item => {
        this.multipleSelection.forEach(val => {
          if (item.id == val.id) {
            stocks.push({
              "id": val.id,
              "name": val.name,
              "actualInv": val.actualInv,
              "lockInv": val.lockInv,
              "useInv": val.useInv,
              "material": val.material,
              "width": val.width,
              "spec": val.spec,
              "length": val.length,
              "thick": val.thick,
              "isRemanent": val.isRemanent,
              "drawingUrl": val.drawingUrl,
              "previewUrl": val.previewUrl
            });
            if ((!item.numVal && !isNumber(item.numVal) || item.numVal < 0 || item.numVal > item.syInv)) {
              isAllNumAdd = false;
            }
          }
        });
      });
      if (!isAllNumAdd) return this.$message.error('已选库存中数量未填写或填写数量大于仓库数量，请重新填写');
      tabsItem.taskParts.forEach(item=>{
        lockData.push({taskId:item.taskId,partId:item.part.id,numVal:item.numVal})
        formTaskParts.push({
          taskId: item.taskId,
          partId: item.part.id,
          part:item.part,
          numVal:item.numVal
        })
      })
      let formData = {
        Parts: formTaskParts,
        stocks
      };
      let isLine=await this.$hubClient.sendlsClientOnline('cad');
      if(isLine === false){
        this.$hubClient.sendOpenClient();
      }
      this.lockPartNums(lockData,formData,isLine);
    },
    lockPartNums(lockData,formData,isLine){
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.SET_LAYOUT_LOCK,lockData)
        .then(res => {
          loading.close();
          // 保存排样数据
          this.$store.dispatch('resource/setUploadLayoutInfo', formData);
          // 刷新零件列表
          this.$store.dispatch('app/setPartRefreshList');
          // 启动CAD
          if(isLine === true){
            this.$hubClient.sendLayout(formData)
          }else{
            this.$hubClient.sendOpenClient();
          }
          this.$message.success('排样数据已发送CAD,请等待CAD处理');
          let tabList=clone(this.tabList);
          if(tabList.length == 1){
            this.handleShare();
          }else{
            this.tabList = tabList.splice(this.activeName,1);
            this.activeName='0';
            this.handleClick();
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    getPaneLabel(val) {
      let gasName = '';
      if (val.gas == 0) {
        gasName = '空气';
      }
      return `${val.material}-${val.thick}mm-${gasName}`;
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getAssteImage(url){
      return url && isString(url)?(globalJs.isAbsolutePath(url)?url:this.$API.ASSERT_SERVER_URL+url):'';
    }
  }
};
</script>
<style lang="less">
.workscheduling-container {}
</style>
